package com.vimi8.chick.plugins.activity

import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.view.ViewCompat
import android.support.v7.app.AppCompatActivity
import android.transition.Transition
import android.util.Log
import android.view.View
import com.afollestad.materialdialogs.MaterialDialog
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.model.VideoOptionModel
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.vimi8.chick.plugins.R
import kotlinx.android.synthetic.main.activity_monitor.*
import tv.danmaku.ijk.media.player.IjkMediaPlayer

class MonitorActivity : AppCompatActivity() {
    private var playerSupport = false
    private var orientationUtils: OrientationUtils? = null
    private var url: String? = null
    private var title = "视频"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_monitor)

        url = intent.getStringExtra("url")
        val t = intent.getStringExtra("title")
        if (!t.isNullOrEmpty()) title = t

        initPlayer()
    }

    private fun initPlayer() {
        try {
            IjkMediaPlayer.loadLibrariesOnce(null)
            playerSupport = true

            if (playerSupport) {
                // 优化加载速度，降低延迟
                val list = arrayListOf<VideoOptionModel>()
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_transport", "tcp"))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "rtsp_flags", "prefer_tcp"))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "allowed_media_types", "video"))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "timeout", 20000))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "buffer_size", 1316))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "infbuf", 1))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "analyzemaxduration", 100))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "probesize", 10240))
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "flush_packets", 1))
                // 关闭播放器缓冲，这个必须关闭，否则会出现播放一段时间后，一直卡主，控制台打印 FFP_MSG_BUFFERING_START
                list.add(VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "packet-buffering", 0))
                GSYVideoManager.instance().optionModelList = list

                orientationUtils = OrientationUtils(this@MonitorActivity, player)

                // bug: 全屏不能播放，暂时隐藏
                player.fullscreenButton.visibility = View.GONE

                // 设置全屏按键功能，这是使用的是旋转屏幕，而不是全屏
                player.fullscreenButton.setOnClickListener {
                    orientationUtils?.resolveByClick()
                }
                // 设置返回键
                player.backButton.setOnClickListener { onBackPressed() }
                // 是否可以滑动调整
                player.setIsTouchWiget(true)

                player.setUp(url, true, title)

                play()
            }
        } catch (e: Throwable) {
            Log.e("GiraffePlayer", "loadLibraries error", e)
        }
    }

    private fun play() {
        if (!playerSupport) {
            MaterialDialog.Builder(this@MonitorActivity)
                .title("播放失败")
                .content("播放器不支持此设备")
                .positiveText("确认")
                .negativeText("取消")
                .show()
            return
        } else if (url.isNullOrEmpty()) {
            MaterialDialog.Builder(this@MonitorActivity)
                .title("播放失败")
                .content("没有播放地址")
                .positiveText("确认")
                .negativeText("取消")
                .show()
            return
        }

        player.startPlayLogic()
    }

    override fun onResume() {
        super.onResume()
        player.onVideoResume()
    }

    override fun onPause() {
        super.onPause()
        player.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        orientationUtils?.releaseListener()
    }

    override fun onBackPressed() {
        if (orientationUtils?.screenType == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            player.fullscreenButton.performClick()
            return
        }
        // 释放所有
        player.setVideoAllCallBack(null)
        GSYVideoManager.releaseAllVideos()
        super.onBackPressed()
    }
}
